package com.shux.usermanager.biz.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shux.common.exception.ShuxRunTimeException;
import com.shux.usermanager.biz.ISysMenuBiz;
import com.shux.usermanager.dao.ISysMenuDao;
import com.shux.usermanager.entity.SysMenu;
import com.shux.usermanager.utils.MenuTreeUtil;
import com.shux.utils.other.RightsHelper;

/**
 **********************************************
 *  描述：系统菜单相关BIZ
 * Simba.Hua
 * 2017年6月18日
 **********************************************
**/
@Service("sysMenuBiz")
public class SysMenuBizImpl implements ISysMenuBiz {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private @Autowired ISysMenuDao sysMenuDao;
    
    @Override
    public List<SysMenu> queryMenusByParentId(Integer parentId) {
        List<SysMenu> allMenus = queryAllMenu();
        MenuTreeUtil treeMenu = new MenuTreeUtil(allMenus);
        return treeMenu.generateTreeNode(parentId).getSubSysMenu();
    }
    @Override
    public List<SysMenu> queryAllMenu() {
        try {
            return sysMenuDao.getAllMenu();
        } catch (Exception e) {
            logger.error("获得全部菜单失败！",e);
            throw new ShuxRunTimeException("获得全部菜单失败！",e);
        }
    }
    @Override
    public List<SysMenu> queryMenusRoot() {
        return queryMenusByParentId(0);
    }
    
    /**
     * 根据角色权限获取本权限的菜单列表(递归处理)
     * 
     * @param menuList
     *            ：传入的总菜单
     * @param roleRights
     *            ：加密的权限字符串
     * @return
     */
    public List<SysMenu> checkMenu(List<SysMenu> menuList, String roleRights) {
      for (int i = 0; i < menuList.size(); i++) {
        menuList.get(i).setHasSysMenu(RightsHelper.testRights(roleRights, menuList.get(i).getMenuId()));
        if (menuList.get(i).isHasSysMenu()) { // 判断是否有此菜单权限
          this.checkMenu(menuList.get(i).getSubSysMenu(), roleRights);// 是：继续排查其子菜单
        } else {
          menuList.remove(i);
          i--;
        }
      }
      return menuList;
    }
    
    

}
